package com.quanyan.club.service.impl;

import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbActivity;
import com.quanyan.club.entity.db.TbClub;
import com.quanyan.club.entity.vo.req.ReqClubCommentPage;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.entity.vo.resp.RespClubComment;
import com.quanyan.club.entity.vo.resp.RespClubMark;
import com.quanyan.club.mapper.TbActivityMapper;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.service.ClubActivityService;
import com.quanyan.club.service.ClubCommentService;
import com.quanyan.comment.reqeust.ReqBaseParam;
import com.quanyan.comment.reqeust.ReqCommentQuery;
import com.quanyan.comment.response.RespComment;
import com.quanyan.comment.response.RespCommentDetailScore;
import com.quanyan.comment.response.RespCommentSum;
import com.quanyan.comment.response.RespPicture;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import jodd.util.MathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zhang on 16/7/19.
 */
@Service("clubCommentService")
public class ClubCommentServiceImpl implements ClubCommentService {

    private static final Logger logger = LoggerFactory.getLogger(ClubCommentServiceImpl.class);

    @Autowired
    private CommentServiceFacade commentServiceFacade;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ClubActivityService clubActivityService;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbActivityMapper tbActivityMapper;

    /**
     * 获取俱乐部评分
     * @param clubId
     * @param uid
     * @return
     */
    @Override
    public RespClubMark getClubMark(int clubId, int uid) {
        RespClubMark respClubMark = new RespClubMark();
        ReqBaseParam param = new ReqBaseParam();
        param.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
        param.setSystemCode(Constants.CLUB_SYSTEM_CODE);
        param.setBusinessId(clubId);
        RespCommentSum respCommentSum = this.commentServiceFacade.queryCommentSum(param);
        ReqCommentQuery queryStar = new ReqCommentQuery();
        queryStar.setCommonParam(clubId);
        queryStar.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
        queryStar.setSystemCode(Constants.CLUB_SYSTEM_CODE);

        int zeroStar = 0;
        int oneStar = 0;
        int twoStar = 0;
        int threeStar = 0;
        int fourStar = 0;
        int fiveStar = 0;
        double star = 0;
        int commentCount = 0;
        if (respCommentSum != null) {
            zeroStar = respCommentSum.getStarZero();
            oneStar = respCommentSum.getStarOne();
            twoStar = respCommentSum.getStarTwo();
            threeStar = respCommentSum.getStarThree();
            fourStar = respCommentSum.getStarFour();
            fiveStar = respCommentSum.getStarFive();
            commentCount = respCommentSum.getClubCommentCount();
        }
        TbClub club = this.clubMapper.selectByPrimaryKey(clubId);
        if(club != null){
            respClubMark.setClubName(club.getClubName());
            respClubMark.setClubLogo(club.getLogoUrl());
        }else{
            respClubMark.setClubName("");
            respClubMark.setClubLogo("");
        }
        APIResponse<List<RespCommentDetailScore>> starResponse =
                commentServiceFacade.getRespCommentDetailScoreSum(queryStar);
        logger.warn("请求俱乐部评价平均分：" + JSONObject.toJSONString(starResponse));
        star = club.getStar();
        logger.warn("star:" + star);
        double clubStarNewSum = 0;
        double activityStarNewSum = 0;
        double clubStar = 0;
        double activityStar = 0;
        double x = 0;
        clubStar = activityStar = star/club.getActivityCount();
        if(starResponse.isRet())
        {
            List<RespCommentDetailScore> scores = starResponse.getData();
            if(null != scores && scores.size() > 0)
            {
                clubStarNewSum = scores.get(0).getSumScore();
                activityStarNewSum = scores.get(1).getSumScore();
                if(club.getActivityCount() > scores.get(0).getCount())
                {
                    int oldCount = club.getActivityCount() - scores.get(0).getCount();
                    double oldStar = Math.abs(star*2 - clubStarNewSum - activityStarNewSum)/2.0;
                    clubStar = (clubStarNewSum + oldStar)/club.getActivityCount();
                    activityStar = (activityStarNewSum + oldStar)/club.getActivityCount();
                }
            }
        }
        respClubMark.setClubStar(clubStar);
        respClubMark.setActivityStar(activityStar);
        respClubMark.setClubId(clubId);
        respClubMark.setStar((double)Math.round(star/club.getActivityCount()));
        respClubMark.setCommentCount(commentCount);
        respClubMark.setStarZero(zeroStar);
        respClubMark.setStarOne(oneStar);
        respClubMark.setStarTwo(twoStar);
        respClubMark.setStarThree(threeStar);
        respClubMark.setStarFour(fourStar);
        respClubMark.setStarFive(fiveStar);
        List<RespClubComment> respClubComments = new ArrayList<RespClubComment>();
        //判断是否有评论存在
        if (commentCount > 0) {
            ReqClubCommentPage reqClubCommentPage = new ReqClubCommentPage();
            reqClubCommentPage.setPageSize(2);
            reqClubCommentPage.setPageNum(0);
            reqClubCommentPage.setClubId(clubId);
            PageObj<List<RespClubComment>> commentPageObj = getClubCommentList(reqClubCommentPage);
            if(null != commentPageObj.getItems() && commentPageObj.getItems().size() > 0)
            {
                respClubComments = commentPageObj.getItems();
            }
            respClubMark.setRespClubCommentList(respClubComments);
        }else{
            respClubMark.setRespClubCommentList(respClubComments);
        }
        return respClubMark;
    }

    /**
     * 获取俱乐部评论列表
     * @param reqClubCommentPage
     * @return
     */
    @Override
    public PageObj<List<RespClubComment>> getClubCommentList(ReqClubCommentPage reqClubCommentPage) {
        ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
        reqCommentQuery.setCommonParam(reqClubCommentPage.getClubId());
        reqCommentQuery.setBusinessId(reqClubCommentPage.getActivityId());
        reqCommentQuery.setSystemCode(Constants.CLUB_SYSTEM_CODE);
        reqCommentQuery.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
        reqCommentQuery.setFlagRelay(reqClubCommentPage.isFlagRelay());
        reqCommentQuery.setPageNum(reqClubCommentPage.getPageNum());
        reqCommentQuery.setPageSize(reqClubCommentPage.getPageSize());
        PageObj<List<RespClubComment>> pageObj = new PageObj<>();
        APIResponse<PageObj<List<RespComment>>> respCommentPage = null;
        try{
            respCommentPage = this.commentServiceFacade.commentQuery(reqCommentQuery);
        }catch (RpcException rc)
        {
            logger.warn("调用评价系统失败", rc.getMessage());
            return pageObj;
        }
        logger.warn("评价返回:{}", respCommentPage);
        if(respCommentPage.isRet()){
            pageObj.setPageCount(respCommentPage.getData().getPageCount());
            pageObj.setPageNum(respCommentPage.getData().getPageNum());
            pageObj.setTotal(respCommentPage.getData().getTotal());
            pageObj.setSize(respCommentPage.getData().getSize());
            List<RespComment> respCommentList = respCommentPage.getData().getItems();
            List<RespClubComment> respClubCommentList = new ArrayList<>();
            RespClubComment respClubComment;
            for (RespComment respComment : respCommentList) {
                respClubComment = new RespClubComment();
                respClubComment.setLevel(0);
                respClubComment.setClubActivityId(respComment.getBusinessId());
                respClubComment.setContent(respComment.getCommentContent());
                if (respComment.getScore()==null) {
                    respClubComment.setStar(0);
                }else{
                    respClubComment.setStar((int)Math.round(respComment.getScore()));
                }
                respClubComment.setCreateTime(respComment.getCreateTime().getTime());
                int fromUser = respComment.getFromUser();
                respClubComment.setUid(fromUser);
                APIResponse<RespUserInfoDetail> response = userServiceFacade.queryUserInfoDetail(fromUser);
                if (response.isRet() && null != response.getData()) {
                    if (response.getData().getIsBidsVerifyDe() == 1 || response.getData().getIsBuyoutVerifyDe() == 1) {
                        respClubComment.setIsTalent(1);
                    } else {
                        respClubComment.setIsTalent(0);
                    }

                    if(respComment.getAnonymous() == Constants.BYTE_ONE){
                        respClubComment.setNickName("匿名用户");
                    }else{
                        respClubComment.setNickName(response.getData().getNickName());
                        respClubComment.setLevel(response.getData().getLevelDe());
                        respClubComment.setIcon(response.getData().getIcon());
                        if (response.getData().getIsBidsVerifyDe() == 1 || response.getData().getIsBuyoutVerifyDe() == 1) {
                            respClubComment.setIsTalent(1);
                        } else {
                            respClubComment.setIsTalent(0);
                        }
                    }
                    respClubComment.setUid(fromUser);
                }else{
                    respClubComment.setNickName("");
                    respClubComment.setLevel(0);
                    respClubComment.setIcon("");
                    respClubComment.setIsTalent(0);
                    respClubComment.setUid(0);
                }
                TbActivity tbActivity = tbActivityMapper.selectByPrimaryKey(respComment.getBusinessId());
                if (null != tbActivity) {
                    respClubComment.setClubActivityName(tbActivity.getName());
                }
                List<RespPicture> pics = respComment.getLstPic();
                List<String> urls = new ArrayList<String>();
                logger.warn("评价图片：{}", pics);
                if(null != pics && pics.size() > 0){
                    for(RespPicture r : pics)
                    {
                        urls.add(r.getPicUrl());
                    }
                }else{
                    respClubComment.setPicUrls(new ArrayList<String>());
                }
                respClubComment.setPicUrls(urls);
                respClubComment.setNowServerTime(new Date());
                List<RespComment> replayComments = respComment.getLstReplayComment();
                logger.warn("replay:" + JSONObject.toJSONString(replayComments));
                List<RespClubComment> clubReplayComments = new ArrayList<RespClubComment>();
                if(null != replayComments && replayComments.size() > 0)
                {
                    for(RespComment comment : respComment.getLstReplayComment())
                    {
                        logger.warn("回复：" + JSONObject.toJSONString(comment));
                        RespClubComment clubReplayComment = new RespClubComment();
                        clubReplayComment.setUid(comment.getFromUser());
                        clubReplayComment.setContent(comment.getCommentContent());
                        clubReplayComment.setNickName("管理员回复");
                        clubReplayComments.add(clubReplayComment);
                    }
                    respClubComment.setRespClubComments(clubReplayComments);
                }
                respClubComment.setCommentId(respComment.getId());
                respClubCommentList.add(respClubComment);
            }
            pageObj.setItems(respClubCommentList);
        }
        return pageObj;
    }

    private int updateClubStar(Integer star,Integer clubId){
        TbClub club = new TbClub();
        club.setStar((double)star);
        club.setId(clubId);
        int n = clubMapper.updateByPrimaryKeySelective(club);
        return n;
    }
}
